package com.homedo.async.mysql.support.prepare.insert;

import com.blinkfox.zealot.bean.SqlInfo;
import com.blinkfox.zealot.core.ZealotKhala;
import com.google.common.collect.Lists;
import com.homedo.async.mysql.support.meta.EntityMetaData;
import com.homedo.async.mysql.support.prepare.util.CollectRecordColumnValUtil;
import com.homedo.plainly.logger.Logger;
import com.homedo.plainly.logger.LoggerFactory;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author jgshun
 * @date 2020/3/5 1:56 PM
 */
public abstract class Record2Sql4Insert {
    private static final Logger _LOGGER = LoggerFactory.getLogger(Record2Sql4Insert.class);

    public static <T> Object[] prepare(T record, EntityMetaData<T> entityMetaData, boolean includeNullVals) {
        Object[] prepareSelectSql = new Object[2];

        ZealotKhala sqlKhala = ZealotKhala.start()
                .insertInto(entityMetaData.getTableName());

        Map<String, Object> columnNameValMap = CollectRecordColumnValUtil.collect(record, entityMetaData, includeNullVals);

        List<Object> allColumnVals = Lists.newArrayList();

        if (!columnNameValMap.isEmpty()) {
            sqlKhala.text(" ( ").text(columnNameValMap.keySet().stream().collect(Collectors.joining(", "))).text(" ) ");

            sqlKhala.values(" ( ");

            List<Object> columnVals = columnNameValMap.keySet().stream().map(e -> {
                return columnNameValMap.get(e);
            }).collect(Collectors.toList());

            allColumnVals.addAll(columnVals);

            sqlKhala.text(columnVals.stream().map(e -> " ? ").collect(Collectors.joining(", ")));

            sqlKhala.text(" ) ");
        } else {
            _LOGGER.error("[缺少插入数据：{}]", sqlKhala.end().getSql());
            throw new RuntimeException("[缺少插入数据]");
        }

        sqlKhala.param(allColumnVals);

        SqlInfo sqlInfo = sqlKhala.end();

        prepareSelectSql[0] = sqlInfo.getSql();
        prepareSelectSql[1] = sqlInfo.getParams();

        return prepareSelectSql;
    }

}

